package ecoll.server;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class FileUploadServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		BlobstoreService blobstoreService = BlobstoreServiceFactory
				.getBlobstoreService();
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(request);

		BlobKey blobKey = blobs.get("myFile");
		if (blobKey == null) {
			throw new ServletException("Blobstore error - file not uploaded!");
		} else {
			Key userKey = KeyFactory.createKey("UserEntity", Server.getUser());
			Key fileKey = Database.putFile(blobKey, new Date());
			Database.putRights(userKey, fileKey, new Date(), "o");
			response.sendRedirect("upload?blobKey=" + blobKey.getKeyString());
		}
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {
			BlobKey blobKey = new BlobKey(request.getParameter("blobKey"));
			// response.setContentType("application/force-download");
			// response.setHeader("Content-Transfer-Encoding", "binary");
			// response.setHeader("Content-Disposition",
			// "attachment; filename= fileName.extension");
			BlobstoreService blobstoreService = BlobstoreServiceFactory
					.getBlobstoreService();
			blobstoreService.serve(blobKey, response);
		} catch (Exception e) {
			String result = "FAIL: File haven't been uploaded\n";
			response.getWriter().println(
					result + "Exception : " + e.getMessage());
		}

		// String info = request.getParameter("info");
		// response.setContentType("text/html");
		// response.getWriter().println(info);
	}

}
